import json
import time

from django.http import JsonResponse

from blueking.component.shortcuts import get_client_by_request
from home_application.constant import JOB_BK_BIZ_ID, BACKED_FILE_PLAN_ID, WAITING_CODE, JOB_RESULT_ATTEMPTS_INTERVAL, \
    SUCCESS_CODE, BK_JOB_HOST, WEB_SUCCESS_CODE
from bk_framework_app.models import BackUpRecord


def backup_file_view(request):
    host_id = request.GET.get('host_id_list')
    host_id_list = [int(bk_host_id) for bk_host_id in host_id.split(',')]
    search_path = request.GET.get('search_path')
    suffix = request.GET.get('suffix')
    client = get_client_by_request(request)
    # 调用执行方案
    kwargs = {
        'bk_scope_type': 'biz',
        'bk_scope_id': JOB_BK_BIZ_ID,
        "job_plan_id": BACKED_FILE_PLAN_ID,
        "global_var_list": [
            {
                "name": "host_list",
                "server": {
                    "host_id_list": host_id_list,
                }
            },
            {
                "name": "backup_path",
                "value": request.GET.get('backup_path')
            },
            {
                "name": "search_path",
                "value": search_path,
            },
            {
                "name": "suffix",
                "value": suffix,
            }
        ]
    }
    result = client.jobv3.execute_job_plan(**kwargs)
    instance_id = result.get("data").get("job_instance_id")

    kwargs = {
        "bk_scope_type": "biz",
        "bk_scope_id": JOB_BK_BIZ_ID,
        "job_instance_id": instance_id
    }
    attempts = 0
    while attempts < 10:
        result = client.jobv3.get_job_instance_status(**kwargs)
        instance_list = result.get("data").get("step_instance_list")
        status = instance_list[0].get("status")
        if status == WAITING_CODE:
            time.sleep(JOB_RESULT_ATTEMPTS_INTERVAL)
        elif status != SUCCESS_CODE:
            res_data = {
                "result": False,
                "code": 0,
                "message": "执行失败"
            }
            return res_data
        else:
            break
        attempts += 1
    step_instance_id = instance_list[0].get("step_instance_id")
    for bk_host_id in host_id_list:
        kwargs = {
            "bk_scope_type": "biz",
            "bk_scope_id": JOB_BK_BIZ_ID,
            "job_instance_id": instance_id,
            "step_instance_id": step_instance_id,
            "bk_host_id": bk_host_id
        }
        result = client.jobv3.get_job_instance_ip_log(**kwargs)
        step_res = result.get("data").get("log_content")
        json_step_res = json.loads(step_res)
        for step_res in json_step_res:
            # 创建备份记录
            step_res["bk_host_id"] = bk_host_id
            step_res["bk_file_dir"] = search_path
            step_res["bk_file_suffix"] = suffix
            step_res["bk_file_operator"] = request.user.username
            step_res["bk_job_link"] = "{}/biz/{}/execute/task/{}".format(
                BK_JOB_HOST,
                JOB_BK_BIZ_ID,
                instance_id,
            )
            step_res['bk_backup_time'] = step_res['bk_file_create_time']
            model_fields = [f.name for f in BackUpRecord._meta.get_fields()]
            # 只保留模型中存在的字段
            filtered_step_res = {k: v for k, v in step_res.items() if k in model_fields}
            BackUpRecord.objects.create(**filtered_step_res)


    res_data = {
        "result": True,
        "code": WEB_SUCCESS_CODE,
        "data": "执行成功"
    }
    return JsonResponse(res_data)


def get_backup_record(request):
    """
    查询备份记录
    :param request:
    :return:
    """
    res_data = {
        "result": True,
        "data":list(BackUpRecord.objects.all().order_by("-id").values()),
        "code":WEB_SUCCESS_CODE
    }
    return JsonResponse(res_data)
